package com.cj.gateway.jwtutil;

import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;

/**
 * @Author cheng jun
 * @Description:
 * @Date 2021/5/30 20:42
 */
@Slf4j
public class JWTUtil {

    private  String jwtKey;

    private  String jwtTtl;

    public JWTUtil() {
    }

    public JWTUtil(String jwtKey, String jwtTtl) {
        this.jwtKey = jwtKey;
        this.jwtTtl = jwtTtl;
    }

    /**
     * 创建token
     *
     * @param id
     * @param payload
     * @param ttlMillis
     * @return
     */
    public String createJWT(String id, String payload, Long ttlMillis) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        if (ttlMillis == null) {
            ttlMillis = Long.parseLong(jwtTtl);
        }
        long expMillis = nowMillis + ttlMillis;
        Date expDate = new Date(expMillis);
        SecretKey secretKey = generalKey();

        JwtBuilder builder = Jwts.builder();
        // 唯一的ID
        builder.setId(id);
        // JSON数据
        builder.setSubject(payload);
        // 签发者
        builder.setIssuer("admin");
        // 签发时间
        builder.setIssuedAt(now);
        // 使用HS256对称加密算法签名, 第二个参数为秘钥
        builder.signWith(signatureAlgorithm, secretKey);
        // 设置过期时间
        builder.setExpiration(expDate);
        log.info("JWT内容-------------------------------------:" + builder.compact());

        return builder.compact();
    }

    /**
     * 生成加密后的秘钥 secretKey
     *
     * @return
     */
    public SecretKey generalKey() {
        byte[] encodedKey = Base64.getDecoder().decode(jwtKey);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");

        return key;
    }

    /**
     * 解析
     *
     * @param jwt
     * @return
     * @throws Exception
     */
    public Claims parseJWT(String jwt) throws Exception {
        // 不管是否过期，都返回claims对象
        Claims claims = null;
        SecretKey secretKey = generalKey();
        try {
            claims = Jwts.parser()
                    // 设置标识名
                    .setSigningKey(secretKey)
                    // 解析token
                    .parseClaimsJws(jwt)
                    .getBody();
        } catch (ExpiredJwtException e) {
            claims = e.getClaims();
        }

        return claims;
    }
}
